<template>
  <div class="bimface-project" v-bind="$attrs">
    <div id="bimface" :ref="bimfaceId"></div>
  </div>
</template>

<script>
export default {
  name: 'bimfaceProject',
  props: {
    /**
     * BIMFACE JSSDK加载器的配置信息
     * @param APIHost {String} API URL
     * @param language {String} 语言版本：zh_CN - 中文版；en_GB - 英文版
     * @param staticHost {String} 静态资源地址
     * @param version {String} JSSDK版本号（缺省值：最新版本）
     * @param ViewToken {String} 图纸对应token
     * @param visualStyle {String} 显示效果
     * @param ...other 其它配置项
     */
    loaderOptions: {
      type: Object,
      default: () => ({})
    },
    /**
     * WebApplication3D的配置
     * @param Buttons {Array} 获取工具条button对象
     * @param navigatorType {String} 强制浏览UI为移动端/网页端，枚举值为"Web", "Mobile"
     * @param Toolbars {Array} 获取工具条或者目录树(MainToolbar:工具条；ModelTree：目录树)
     * @param ...other 其它配置项
     */
    webAppOptions: {
      type: Object,
      default: () => ({
        enableBorderLine: false
      })
    },
    // 指定当前渲染类型 3DView （模型）drawingView（图纸）
    viewType: {
      type: String,
      default: ''
    },
    // 单模型需要传图纸id
    drawingId: {
      type: [String, Number],
      default: ''
    },
    // 集成模型需要传图纸id和单模型的fileid
    fileId: {
      type: String,
      default: ''
    },
    // 获取到图层对象后调用事件
    eventFn: {
      type: Function,
      default: null
    },
    // 图层加载完毕
    viewAddedFn: {
      type: Function,
      default: null
    },
    // 加载成功之后的回调
    successFn: {
      type: Function,
      default: null
    },
    // 加载失败之后的回调
    failFn: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      hasInit: false,
      bimfaceId: `bimface${this.$getRandomNum()}`,
      // 图纸渲染的节点
      rootDom: null,
      // app对象
      viewApp: null,
      // 模型(图纸)对象
      viewer: null,
      // 模型或图纸
      type: '',
      preToken: '',
      // 重载token
      newToken: '',
      // 图层配置信息
      viewMetaData: null
    };
  },
  watch: {
    loaderOptions: {
      deep: true,
      handler: function (data) {
        if (data && data.viewToken) {
          this.init();
        }
      }
    }
  },
  computed: {
    // 获取工具条
    toolbars() {
      if (!this.viewApp || !this.viewApp.getToolbars) return [];
      return this.viewApp.getToolbars();
    },
    // bimface token
    viewToken() {
      const hasObj = this.$checkType(this.loaderOptions) === 'object';
      return hasObj ? this.loaderOptions.viewToken : '';
    }
  },
  mounted() {
    this.rootDom = this.$refs[this.bimfaceId];
    // window.addEventListener('resize', this.resize);
  },
  beforeDestroy() {
    this.destroyView();
    // window.removeEventListener('resize', this.resize);
  },
  methods: {
    /**
     * 初始化bimface图纸
     * @param token 手动传入token
     */
    init(token) {
      if ((!this.viewToken && !this.newToken) || !this.rootDom) return;
      try {
        const children = this.$refs[this.bimfaceId].children;
        for (let i = 0; i < children.length; i++) {
          this.$refs[this.bimfaceId].removeChild(children[i]);
        }
        // 设置BIMFACE JSSDK加载器的配置信息
        const loaderConfig = {
          ...new BimfaceSDKLoaderConfig(),
          ...this.loaderOptions,
          viewToken: this.newToken || this.viewToken,
        };
        if (this.viewType) loaderConfig.viewType = this.viewType;
        this.hasInit = true;
        this.preToken = loaderConfig.viewToken;
        // 加载BIMFACE JSSDK加载器
        BimfaceSDKLoader.load(loaderConfig, this.succesFnCheck, this.failCallBack);
      } catch (e) {}
    },
    /**
     *
     * 清除当前图纸、重载bimface图纸
     * @param token 手动传入token
     */
    reload(token) {
      this.newToken = token;
      this.init(token);
    },
    /**
     * 判断加载模型或者图纸
     */
    succesFnCheck(viewMetaData) {
      console.log('viewMetaData', viewMetaData);
      this.viewMetaData = viewMetaData;
      if (typeof this.successFn === 'function') {
        return this.successFn(viewMetaData, this.rootDom);
      }
      this.type = this.viewType || viewMetaData.viewType;
      if (this.type === '3DView') {
        return this.successCallback3D();
      } else if (this.type === 'drawingView') {
        return this.successCallback2D();
      }
    },
    /**
     * 模型加载成功回调(3D)
     */
    async successCallback3D() {
      // 创建WebApplication3DConfig
      const webAppConfig = new Glodon.Bimface.Application.WebApplication3DConfig();
      // 设置创建WebApplication3DConfig的dom元素值
      webAppConfig.domElement = this.rootDom;
      // 创建WebApplication3D
      this.viewApp = new Glodon.Bimface.Application.WebApplication3D({
        ...webAppConfig,
        ...this.webAppOptions
      });
      // 获取viewer3D对象
      this.viewer = this.viewApp.getViewer();
      // 添加待显示的模型
      this.viewApp.addView(this.newToken || this.viewToken);
      if (typeof this.eventFn === 'function') {
        await this.eventFn(this.viewer, this.viewApp, this.viewMetaData);
      }
      // biamface图层加载完毕
      this.viewMounted();
    },
    /**
     * 图纸加载成功回调(2D)
     */
    // async successCallback2D() {
    //   // 创建ViewerDrawingConfig
    //   const webAppConfig = new Glodon.Bimface.Application.WebApplicationDrawingConfig();
    //   // 设置创建WebApplicationDrawingConfig的dom元素值
    //   webAppConfig.domElement = this.rootDom;
    //   // 创建ViewerDrawing
    //   this.viewApp = new Glodon.Bimface.Application.WebApplicationDrawing({
    //     ...webAppConfig,
    //     ...this.webAppOptions
    //   });
    //   // 加载图纸
    //   this.drawingId && this.viewApp.load(this.viewToken);
    // },
    /**
     * 图纸加载成功回调(2D)
     */
    async successCallback2D() {
      // 创建ViewerDrawingConfig
      const webAppConfig = new Glodon.Bimface.Viewer.ViewerDrawingConfig();
      // 设置创建WebApplicationDrawingConfig的dom元素值
      webAppConfig.domElement = this.rootDom;
      // 创建ViewerDrawing
      this.viewApp = new Glodon.Bimface.Viewer.ViewerDrawing({
        ...webAppConfig,
        ...this.webAppOptions
      });
      // 加载图纸
      if (this.drawingId) {
        if (this.fileId) {
          // 集成模型需要传图纸id和单模型的fileid
          this.viewApp.load(this.newToken || this.viewToken, String(this.drawingId), this.fileId);
        } else {
          // 单模型需要传图纸id
          this.viewApp.load(this.newToken || this.viewToken, String(this.drawingId));
        }
      } else {
        this.viewApp.load(this.newToken || this.viewToken);
      }
      // 获取二维矢量图纸对象
      // this.viewer = this.viewApp.getViewer();
      if (typeof this.eventFn === 'function') {
        await this.eventFn(this.viewer, this.viewApp, this.viewMetaData);
      }
      // biamface图层加载完毕
      this.viewMounted();
    },
    /**
     * biamface图层加载完毕
     */
    viewMounted() {
      this.evtListener('add');
    },
    /**
     * 绑定（解绑）事件
     * @param type {String} remove: 解绑、add: 绑定
     */
    evtListener(type = 'add') {
      const hasFn = typeof this.viewAddedFn === 'function';
      if (!hasFn || !this.viewMetaData) return;
      const evtFn = this.type === '3DView'
        ? Glodon.Bimface.Viewer.Viewer3DEvent.ViewAdded
        : Glodon.Bimface.Viewer.ViewerDrawingEvent.Loaded;
      const viewAddedFn = () => {
        this.viewAddedFn(this.viewer, this.viewApp, this.viewMetaData);
      };
      if (type === 'remove') {
        (this.viewer || this.viewApp).removeEventListener(evtFn, viewAddedFn);
        return;
      }
      (this.viewer || this.viewApp).addEventListener(evtFn, viewAddedFn);
    },
    /**
     * 图层resize
     */
    resize() {
      if (!this.rootDom) return;
      const position = this.rootDom.getBoundingClientRect();
      const x = position && position.x ? position.x : 0;
      const y = position && position.y ? position.y : 0;
      const el = document.documentElement || document.body;
      this.viewer && this.viewer.resize(el.clientWidth - x, el.clientHeight - y);
    },
    /**
     * 加载失败回调
     */
    failCallBack(error) {
      console.log('bimface init error', error);
      if (typeof this.failFn === 'function') return this.failFn(error);
      const message = this.type === '3DView' ? '模型' : '图纸';
      this.$message.error(`${message}加载失败`);
    },
    /**
     * 销毁当前实例
     * @param viewToken: 当前实例token
     */
    destroyView(viewToken) {
      this.evtListener('remove');
      let token = viewToken || this.viewToken;
      if (this.newToken) {
        token = this.newToken;
      }
      this.newToken = '';
      this.viewMetaData = null;
      // const hasFn = this.viewer && (typeof this.viewer.destroy === 'function');
      // hasFn && this.viewer.destroy(token);
      return {
        viewer: this.viewer,
        currentToken: token
      };
    }
  }
};
</script>

<style scoped lang="scss">
 @import "../../assets/styles/main";

.bimface-project {
  width: 100%;
  height: 100%;
  /*position: absolute;*/
  #bimface {
    width: 100%;
    height: 100%;
    background: linear-gradient(0deg, rgb(246, 250, 255) 10%, rgb(214, 224, 235) 70%);
  }
}
</style>
